package com.yh.concert.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.yh.concert.domain.YhConcertClassify;
import com.yh.concert.domain.YhMerchart;
import com.yh.concert.domain.YhSite;
import com.yh.concert.domain.dto.ConcertDto;
import com.yh.concert.service.IYhConcertClassifyService;
import com.yh.concert.service.IYhMerchartService;
import com.yh.concert.service.IYhSiteService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.yh.concert.domain.YhConcert;
import com.yh.concert.service.IYhConcertService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 演唱会管理Controller
 *
 * @author yh
 * @date 2025-02-26
 */
@Api(tags="演唱会管理管理")
@RestController
@RequestMapping("/concert/concert")
public class YhConcertController extends BaseController
{
    @Autowired
    private IYhConcertService yhConcertService;

    @Autowired
    private IYhMerchartService yhMerchartService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IYhConcertClassifyService concertClassifyService;

    @Autowired
    private IYhSiteService siteService;

    /**
     * 查询演唱会管理列表
     */
    @Anonymous
    @ApiOperation("查询演唱会管理列表")
    @PreAuthorize("@ss.hasPermi('concert:concert:list')")
    @GetMapping("/list")
    public TableDataInfo list(YhConcert yhConcert)
    {
        startPage();
        LoginUser loginUser = getLoginUser();
        if (loginUser.getUserId() == 1){
            yhConcert.setUserId(null);
        }else {
            yhConcert.setUserId(loginUser.getUserId());
        }
        List<YhConcert> list = yhConcertService.selectYhConcertList(yhConcert);

        List<ConcertDto> concertDtos = new ArrayList<>();
        // 查询对应的演唱会名
        for (YhConcert yhConcertRes : list) {
            ConcertDto concertDto = new ConcertDto();
            BeanUtil.copyProperties(yhConcertRes, concertDto);
            YhMerchart one = yhMerchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getId, yhConcertRes.getMerchartId()).eq(YhMerchart::getStatus,1));
            if (BeanUtil.isNotEmpty(one)){
                concertDto.setMerchartName(one.getMerchartName());
            }
            SysUser sysUser = sysUserMapper.selectUserById(yhConcertRes.getUserId());
            if (BeanUtil.isNotEmpty(sysUser)){
                concertDto.setUserName(sysUser.getUserName());
            }
            // 获取分类
            YhConcertClassify one1 = concertClassifyService.getOne(new LambdaQueryWrapper<YhConcertClassify>().eq(YhConcertClassify::getId, yhConcertRes.getClassifyId()));
            if (BeanUtil.isNotEmpty(one1)){
                concertDto.setClassifyName(one1.getClassifyName());
            }
            concertDtos.add(concertDto);

        }
        return getDataTable(concertDtos);
    }

    /**
     * 导出演唱会管理列表
     */

    @ApiOperation("导出演唱会管理列表")
    @PreAuthorize("@ss.hasPermi('concert:concert:export')")
    @Log(title = "演唱会管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhConcert yhConcert)
    {
        List<YhConcert> list = yhConcertService.selectYhConcertList(yhConcert);
        ExcelUtil<YhConcert> util = new ExcelUtil<YhConcert>(YhConcert.class);
        util.exportExcel(response, list, "演唱会管理数据");
    }

    /**
     * 获取演唱会管理详细信息
     */
    @Anonymous
    @ApiOperation("获取演唱会管理详细信息")
//    @PreAuthorize("@ss.hasPermi('concert:concert:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        YhConcert concert = yhConcertService.getById(id);
        ConcertDto concertDto = new ConcertDto();
        BeanUtil.copyProperties(concert,concertDto);
        SysUser sysUser = sysUserMapper.selectUserById(concertDto.getUserId());
        if (BeanUtil.isNotEmpty(sysUser)){
            concertDto.setUserName(sysUser.getUserName());
        }
        Long userId = concertDto.getUserId();
        YhMerchart merchart = yhMerchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getUserId, userId));
        logger.info("获取到的商家信息为：{}",merchart);
        concertDto.setMerchartName(merchart.getMerchartName());
        concertDto.setClassifyName(concertClassifyService.getById(concertDto.getClassifyId()).getClassifyName());
        // 获取场地信息
        YhSite one = siteService.getOne(new LambdaQueryWrapper<YhSite>().eq(YhSite::getId, concertDto.getAddress()));
        concertDto.setSiteName(one.getSiteName());
        concertDto.setSiteAddress(one.getIntro());
        if (BeanUtil.isNotEmpty(concertDto)){
            return AjaxResult.success(concertDto);
        }
        return AjaxResult.error();
    }

    /**
     * 新增演唱会管理
     */
    @ApiOperation("新增演唱会管理")
    @PreAuthorize("@ss.hasPermi('concert:concert:add')")
    @Log(title = "演唱会管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhConcert yhConcert)
    {
        LoginUser loginUser = getLoginUser();
        yhConcert.setUserId(loginUser.getUserId());
        YhMerchart one = yhMerchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getUserId, loginUser.getUserId()).eq(YhMerchart::getStatus,1));
        if (BeanUtil.isNotEmpty(one)){
            yhConcert.setMerchartId(one.getId());
        }else {
            return error("未获取到商家信息");
        }
        yhConcert.setStatus(1L);

        return toAjax(yhConcertService.save(yhConcert));
    }

    /**
     * 修改演唱会管理
     */
    @ApiOperation("修改演唱会管理")
    @PreAuthorize("@ss.hasPermi('concert:concert:edit')")
    @Log(title = "演唱会管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YhConcert yhConcert)
    {
        return toAjax(yhConcertService.updateById(yhConcert));
    }

    /**
     * 删除演唱会管理
     */
    @ApiOperation("删除演唱会管理")
    @PreAuthorize("@ss.hasPermi('concert:concert:remove')")
    @Log(title = "演唱会管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yhConcertService.removeByIds(Arrays.asList(ids)));
    }

    // 查询所有演唱会
    @Anonymous
    @ApiOperation("查询所有演唱会")
    @GetMapping("/listPage")
    public AjaxResult getAllConcert(@RequestParam Integer page,@RequestParam Integer pageSize,@RequestParam String searchQuery ,@RequestParam String selectedCategory){

        // mybatis-plus分页
        Page<YhConcert> pageRes = new Page<>(page, pageSize);
        // 对查询条件判空
        LambdaQueryWrapper<YhConcert> wrapper = new LambdaQueryWrapper<YhConcert>();
        if (StringUtils.isNotBlank(searchQuery)){
            wrapper.like(YhConcert::getConcertName,searchQuery);
        }
        if (StringUtils.isNotBlank(selectedCategory)){
            // 字符串转化为Long
            Long selectedCategoryLong = Long.parseLong(selectedCategory);
            wrapper.eq(YhConcert::getClassifyId,selectedCategoryLong);
        }
        wrapper.eq(YhConcert::getStatus,1);

        wrapper.eq(YhConcert::getDelFlag,0);
        // 查询开始时间还没开始的演唱会
        wrapper.ge(YhConcert::getStartTime,new Date());
        Page<YhConcert> page1 = yhConcertService.page(pageRes,wrapper);

        return AjaxResult.success(page1);
    }
    /**
     * 查询商家数量以及用户数量以及演唱会数量
     */

    @Anonymous
    @GetMapping("getCountIndex")
    public AjaxResult getCounts(){
        // 查询用户数量
        int userCount = sysUserMapper.selectUserCount();
        // 查询商家数量
        Long merchartCount = yhMerchartService.count();
        // 获取演唱会数量
        Long concertCount = yhConcertService.count();
        // 封装数量结果
        Map<String,Object> map = new HashMap<>();
        map.put("userCount",userCount);
        map.put("merchartCount",merchartCount);
        map.put("concertCount",concertCount);
        return AjaxResult.success(map);
    }

    /**
     * 获取正在售票的演唱会信息
     */
    @Anonymous
    @GetMapping("/getAllConcernInfo")
    public AjaxResult getAllConcertInfo(){
        LambdaQueryWrapper<YhConcert> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YhConcert::getStatus,1);
        // 获取开始时间大于当前时间的演唱会
        wrapper.ge(YhConcert::getStartTime,new Date());
        wrapper.orderByAsc(YhConcert::getStartTime);
        List<YhConcert> list = yhConcertService.list(wrapper);
        return AjaxResult.success(list);
    }

    /**
     * 查询未来7天每天有多少场演唱会
     */
    @Anonymous
    @ApiOperation("查询未来7天每天有多少场演唱会")
    @GetMapping("/getConcertCountNext7Days")
    public AjaxResult getConcertCountNext7Days() {
        // 获取当前日期
        Date now = new Date();
        // 计算7天后的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_YEAR, 7);
        Date endDate = calendar.getTime();

        // 查询未来7天内的演唱会
        LambdaQueryWrapper<YhConcert> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(YhConcert::getStartTime, now, endDate);
        wrapper.eq(YhConcert::getStatus, 1);
        List<YhConcert> concerts = yhConcertService.list(wrapper);

        // 按天统计演唱会数量
        Map<String, Long> concertCountByDay = new HashMap<>();
        for (YhConcert concert : concerts) {
            String day = new SimpleDateFormat("yyyy-MM-dd").format(concert.getStartTime());
            concertCountByDay.put(day, concertCountByDay.getOrDefault(day, 0L) + 1);
        }

        // 填充未来7天的日期，确保每天都有数据
        calendar.setTime(now);
        for (int i = 0; i < 7; i++) {
            String day = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            concertCountByDay.putIfAbsent(day, 0L);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }

        return AjaxResult.success(concertCountByDay);
    }

    /**
     * 查询订单量最大的7场演唱会
     */
    @Anonymous
    @ApiOperation("查询当前订单量")
    @GetMapping("/getTop7ConcertsByOrderCount")
    public AjaxResult getTop7ConcertsByOrderCount() {
        // 查询订单量最大的7场演唱会
        Map top7ConcertsByOrderCount = yhConcertService.getTop7ConcertsByOrderCount();
        return AjaxResult.success(top7ConcertsByOrderCount);
    }
}
